<template>
  <!-- 创建采购订单 -->
  <div class="page-container">
    <ex_super_form ref="form" v-bind="option" v-loading="loading" class="common-form-row" label-position="right"
      label-width="140px">
    </ex_super_form>
    <div class="mg_b3">
      <el-button @click="batchRemoval">
        {{ this.$t('label_batch_remove') }}
      </el-button>
      <!-- <el-button @click="batchAdd">
        批量添加商品
      </el-button> -->
      <el-button @click="add">
        {{ this.$t('label_supplier_add_goods') }}
      </el-button>
    </div>
    <ex_super_table ref="table" :model="buildTableModel" :data="rows" class="w_fill purchaseOrderCreationTable"
      @selection-change="e => selection = e">
      <template v-slot:purchaseQtyHeader="scope">
        <div class="flexBox">
          <div class="label_before">{{ $t(scope.model.label) }}</div>
          (<div class="cubs" @click="purchaseQtyClick">{{ $t('label_batch') }}</div>)
        </div>
      </template>
      <template v-slot:purchasePriceHeader="scope">
        <div class="flexBox">
          <div class="label_before">{{ $t(scope.model.label) }}</div>
          (<div class="cubs" @click="purchasePriceClick">{{ $t('label_batch') }}</div>)
        </div>
      </template>
    </ex_super_table>
    <div class="totalCard">
      <el-row>
        <el-col :span="24" :md="16">
          <ex_super_form ref="totalForm" v-bind="totalOption" label-width="150px"></ex_super_form>
        </el-col>
        <el-col :span="24" :md="8">
        <div class="statisticsCard">
        <div>
          <span>
            {{ $t('label_article_category') }}
          </span>
          <span>
            {{ rows.length }}
          </span>
        </div>
        <div>
          <span>
            {{ $t('label_quantity_commodity') }}
          </span>
          <span>
            {{ totalNum }}
          </span>
        </div>
        <div>
          <span>
            {{ $t('label_purchase_total_purchase') }}
          </span>
          <span>
            {{ skuTotalAmount }}
          </span>
        </div>
      </div>
        </el-col>
      </el-row>


    </div>
    <div class="mg_t2 footerSub">
      <!-- <el-checkbox v-model="againChecked">保存后，继续创建下一个</el-checkbox> -->
      <div></div>
      <div>
        <div>
          {{ $t('label_transportation_expenses') }}{{ transportationExpenses }}
        </div>
        <div>
          {{ $t('label_total_payable') }}{{ totalAmount }}
        </div>
      </div>
    </div>
    <div class="mg_t2">
      <el-button type="primary" v-if="!disabled" @click="submitForm(0)">{{
        $t("label_save")
      }}</el-button>
      <el-button type="primary" v-if="!disabled" @click="submitForm(1)">
        {{ $t('label_save_and_submit_review') }}
      </el-button>
      <el-button type="primary" v-if="!disabled" @click="submitForm(2)">
        {{ $t('label_saved_and_approved') }}
      </el-button>
      <el-button @click="return_page_back">{{ $t("label_cancel") }}</el-button>
    </div>
    <add_supply_relationship_dialog ref="addSupplyRelationshipDialog" @selectData="selectData" :dialogData="dialogData"
      :selectData="true" :hasSelectList="rows" />
    <add_source_dialog ref="add_source_dialog" @close="getSourceData" :dialogData="dialogData" />
    <batch_dialog ref="batch_dialog" @submit="batchAmend" />

    <!-- 查看参考价 -->
    <history_purchase_order_dialog ref="historyPurchaseOrderDialog" :dialogData="dialogData" />
  </div>
</template>

<script>
import router_params from "@/mixin/router_params";
import add_supply_relationship_dialog from "@/page/oms/purchase/dialog/add_supply_relationship_dialog.vue"
import add_source_dialog from "@/page/oms/purchase/dialog/add_source_dialog.vue"
import batch_dialog from "@/page/oms/purchase/dialog/batch_dialog.vue"
import history_purchase_order_dialog from "@/page/oms/purchase/dialog/history_purchase_order_dialog.vue"

// 基础采购单数据
const strArr = ["purchaseType", "customerId", "customerName", "customerCode", "supplierId", "supplierName", "supplierOnlyCode", "purchaser", "apportionFreight", "warehouseId", "warehouseName", "warehouseCode", "purchaseSource", "orderNo", "purchaseFreight", "otherCost", "predictDay", "remark"]

export default {
  mixins: [router_params],
  components: {
    add_supply_relationship_dialog,
    add_source_dialog,
    batch_dialog,
    history_purchase_order_dialog,
  },
  props: {},
  data() {
    return {

      // againChecked: false,
      dialogData: {
        customerId: '', // 客户id
      },
      sourceList: [],
      rows: [],
      selection: [],
      edit: false,
      repetition: false,
      disabled: false,
      loading: false,
      option: {
        inputClass: "w_fill",
        default: {
          purchaseType: "GENERAL",
        },
        model: [
          { header: "label_base_info" },
          {
            grid: [
              [
                {
                  span: 1,
                  col: {
                    label: "label_customer",
                    key: "customerId",
                    render: (h, { data, item }) => {
                      // 渲染客户如果存在
                      if (data[item.key]) {
                        this.dialogData.customerId = data[item.key]
                      }
                      return h("common_customer_choose", {
                        props: {
                          value: data[item.key],
                          disabled: (this.edit && !this.repetition)
                        },
                        on: {
                          changeItem: (e) => {
                            const { customerName, customerId, customerCode } = e;
                            this.$set(data, item.key, customerId);
                            this.$set(data, "customerName", customerName);
                            this.$set(data, "customerCode", customerCode);
                            this.$refs.form.$refs.form.clearValidate("customerId");
                            // 切换客户后需要重新选
                            this.dialogData.customerId = customerId
                            this.getSourceData(customerId)
                            // 重置供货商
                            if (data.supplierId) {
                              this.$set(data, "supplierId", '');
                              this.$set(data, "supplierName", '');
                              this.$set(data, "supplierOnlyCode", '');
                            }
                            // 重置采购来源
                            if (data.purchaseSource) {
                              this.$set(data, "purchaseSource", '');
                            }
                          },
                        },
                      });
                    },
                  },
                },
                {
                  span: 1,
                  col: {
                    disabled: true,
                    key: "purchaseType",
                    label: "label_purchase_purchase_type",
                    type: "select",
                    enum: "PurchasePlatformTypeEnum",
                  },
                },

                {
                  span: 1,
                  col: {
                    key: "supplierId",
                    label: "label_supplier",
                    // type: "supplier_select_input",
                    render: (h, { data, item }) => {
                      return h("supplier_select_input", {
                        props: {
                          value: data[item.key],
                          customerId: data.customerId,
                          disabled: (this.edit && !this.repetition)
                        },
                        style: {
                          width: '100%'
                        },
                        on: {
                          changeItem: (e) => {
                            const { supplierName, id, supplierOnlyCode } = e||{supplierName:'',id:'',supplierOnlyCode:''};

                            this.dialogData.supplierName = supplierName
                            this.dialogData.supplierId = id

                            this.$set(data, item.key, id);
                            this.$set(data, "supplierName", supplierName);
                            this.$set(data, "supplierOnlyCode", supplierOnlyCode);
                          },
                        },
                      });
                    },
                  },
                },

                {
                  span: 1,
                  col: {
                    key: "purchaser",
                    label: "label_purchase_buyer",
                  },
                },
                {
                  span: 1,
                  col: {
                    key: "apportionFreight",
                    label: "label_purchase_apportioned_freight",
                    type: "select",
                    enum: "PurchaseApportionFreightEnum",
                  },
                },
                {
                  span: 1,
                  col: {
                    label: "label_purchase_receiving_warehouse",
                    key: "warehouseId",
                    render: (h, { data, item }) => {
                      return h("base_warehouse_select", {
                        props: {
                          value: data[item.key],

                        },
                        style: {
                          width: '100%'
                        },
                        on: {
                          changeItem: (e) => {
                            const { name, id, code } = e;
                            this.$set(data, item.key, id);
                            this.$set(data, "warehouseName", name);
                            this.$set(data, "warehouseCode", code);
                          },
                        },
                      });
                    },
                  },
                },
                {
                  span: 1,
                  col: {
                    key: "purchaseSource",
                    label: "label_purchase_source",
                    render: (h, { data, item }) => {
                      return h("source_select", {
                        props: {
                          value: data[item.key],
                          sourceList: this.sourceList,
                          disabled:data.purchaseType==='ALIBABA',
                        },
                        on: {
                          change: (e) => {
                            this.option.rules.orderNo.required = !!e
                            this.$set(data, item.key, e);
                            if(!e){
                              this.$set(data, 'orderNo', '');
                            }
                          },
                          setSource: () => {
                            this.$refs.form.$refs.form.validateField("customerId");
                            if (this.dialogData.customerId) {
                              this.$refs.add_source_dialog.show(this.sourceList)
                            }
                          }
                        },
                      });
                    },
                  },
                },

                {
                  span: 1,
                  col: {
                    key: "orderNo",
                    label: "label_purchase_tracking_number",
                    if:data=>data.purchaseType==='GENERAL'&&data.purchaseSource
                  },
                },
                {
                  span: 1,
                  col: {
                    key: "platformOrderNo",
                    label: "label_platform_order_1688",
                    if:data=>data.purchaseType==='ALIBABA'&&data.purchaseSource,
                    disabled:true
                  },
                },
              ],
            ],
          },
        ],
        rules: {
          supplierId: [
            {
              required: true,
              message: this.$t("tip_can_no_empty"),
              trigger: "blur",
            },
          ],
          customerId: [
            {
              required: true,
              message: this.$t("tip_can_no_empty"),
              trigger: "blur",
            },
          ],
          purchaseType: [
            {
              required: true,
              message: this.$t("tip_can_no_empty"),
              trigger: "blur",
            },
          ],
          purchaser: [
            {
              required: true,
              message: this.$t("tip_can_no_empty"),
              trigger: "blur",
            },
          ],
          warehouseId: [
            {
              required: true,
              message: this.$t("tip_can_no_empty"),
              trigger: "blur",
            },
          ],
          apportionFreight: [
            {
              required: true,
              message: this.$t("tip_can_no_empty"),
              trigger: "blur",
            },
          ],
          orderNo: {
            required: false,
            message: this.$t("tip_can_no_empty"),
            trigger: "blur",
          },
        },
      },
      totalOption: {
        model: [
          {
            grid: [
              [
                {
                  md:8,
                  span:24,
                  col: {
                    label: 'label_purchase_freight',
                    key: 'purchaseFreight',
                    placeholder: 'label_optional',
                    on: {
                      input: (e) => {
                        const { purchaseFreight, otherCost } = this.$refs.totalForm.getFormData()
                        this.transportationExpenses = Number(purchaseFreight || 0) + Number(otherCost || 0)
                      }
                    },
                    attrs: {
                      type: 'number',
                    },
                  }
                },
                {
                  md:8,
                  span:24,
                  col: {
                    label: 'label_purchase_other_charges',
                    key: 'otherCost',
                    placeholder: 'label_optional',
                    on: {
                      input: (e) => {
                        const { purchaseFreight, otherCost } = this.$refs.totalForm.getFormData()
                        this.transportationExpenses = Number(purchaseFreight || 0) + Number(otherCost || 0)
                      }
                    },
                    attrs: {
                      type: 'number',
                    },
                  }
                },
                {
                  md:8,
                  span:24,
                  col: {
                    label: 'label_expected_arrival',
                    key: 'predictDay',
                    render: (h, { data, item }) => {
                      const items = [
                        { label: this.$t('label_day_within', ['1']), value: '1' },
                        { label: this.$t('label_day_within', ['3']), value: '3' },
                        { label: this.$t('label_day_within', ['5']), value: '5' },
                        { label: this.$t('label_day_within', ['7']), value: '7' },
                        { label: this.$t('label_day_within', ['9']), value: '9' },
                        { label: this.$t('label_day_within', ['15']), value: '15' },
                      ]
                      return h('ex_select_auto', {
                        props: {
                          value: data.predictDay ? String(data.predictDay) : '',
                          items,
                        },
                        on: {
                          change: (e) => {
                            this.$set(data, item.key, e);
                          },
                        }
                      })
                    }
                  }
                },
              ]
            ]
          },
          {
            grid: [
              [
                {
                  // span: 1,
                  col: {
                    label: 'label_purchase_remark',
                    key: 'remark'
                  }
                },
              ]
            ]
          },

        ]
      },
      transportationExpenses: 0,
    };
  },
  watch: {},
  computed: {
    // 应付总额
    totalAmount() {
      let num = this.transportationExpenses + this.skuTotalAmount
      return num
    },
    // 商品数量
    totalNum() {
      let num = 0
      this.rows.forEach(item => {
        num += Number(item.purchaseQty || 0)
      })
      return num
    },
    // 采购总额
    skuTotalAmount() {
      let amount = 0
      this.rows.forEach(item => {
        amount += Number(item.purchaseTotalPrice || 0)
      })
      return amount

    },
    buildTableModel() {
      return [
        {
          type: 'selection',
        },
        {
          key: "skuName",
          label: "label_sku_info",
        },
        {
          key: "skuPrice",
          label: "label_reference_price",
        },
        {
          key: "purchaseQty",
          slot_header: "purchaseQtyHeader",
          label: "label_count",
          width: 160,
          render: (h, { row, column, index }) => {
            return h('el-input', {
              props: {
                value: row.purchaseQty,
                type: 'number',
              },
              on: {
                input: (e) => {
                  row[column.property] = e
                  row['purchaseTotalPrice'] = Number((Number(row.purchasePrice) * Number(row.purchaseQty)).toString().match(/^\d+(?:\.\d{0,3})?/))
                  this.$set(this.rows, index, row)
                }
              }
            })
          }
        },
        {
          key: "purchasePrice",
          label: "label_unit_price",
          slot_header: "purchasePriceHeader",
          width: 160,
          render: (h, { row, column, index }) => {
            return h('el-input', {
              props: {
                value: row.purchasePrice,
                type: 'number',
              },
              on: {
                input: (e) => {
                  row[column.property] = e
                  row['purchaseTotalPrice'] = Number((Number(row.purchasePrice) * Number(row.purchaseQty)).toString().match(/^\d+(?:\.\d{0,3})?/))
                  this.$set(this.rows, index, row)
                }
              }
            })
          }
        },
        {
          key: "historyPurchasePrice",
          label: "label_historical_purchase_price",
          formatter: (r, c, v, i) => (v ? v : "-"),
          render: (h, { row, column, index }) => {
            const showHistory = () => {
              this.$refs.historyPurchaseOrderDialog.show(row)
            }
            let divStr = ''
            if (row['historyPurchasePrice']) {
              divStr = <div onClick={showHistory} class="cubs">{row['historyPurchasePrice']}&nbsp;<i class="el-icon-s-data"></i></div>
            }
            return (
              divStr
            );
          }
        },
        {
          key: "purchaseTotalPrice",
          label: "label_purchase_subtotal",
          formatter: (r, c, v, i) => (v ? v : "-"),
        },
        {
          type: "operate",
          width: 150,
          operate: [
            {
              label: "label_delete",
              click: (row, i) => {
                this.$delete(this.rows, i)
              },
            },
          ],
        },
      ]
    },
  },
  created() { },
  mounted() { },
  methods: {
    batchAmend(data) {
      const { value, type } = data
      this.rows.forEach((item, index) => {
        item[type] = value
        item['purchaseTotalPrice'] = Number(item.purchasePrice) * Number(item.purchaseQty)
        this.$set(this.rows, index, item)
      })
    },
    purchasePriceClick() {
      if (this.rows.length) {
        this.$refs.batch_dialog.show({ title: this.$t('label_revise_unit_price'), name: this.$t('label_unit_price'), key: 'purchasePrice' })
      } else {
        this.$message.error(this.$t('label_no_commodity_to_operate'))
      }
    },
    purchaseQtyClick() {
      if (this.rows.length) {
        this.$refs.batch_dialog.show({ title: this.$t('label_revise_quantity'), name: this.$t('label_count'), key: 'purchaseQty' })
      } else {
        this.$message.error(this.$t('label_no_commodity_to_operate'))
      }
    },
    // 采购来源
    getSourceData(customerId) {
      this.$ajax({
        url: "/oms-api/purchase/OmsPurchaseChannelRpc/selectByCustomerId.json",
        data: { customerId: customerId || this.dialogData.customerId },
        success: (res) => {
          if (res.data && res.data.rows) {
            this.sourceList = res.data.rows
          }
        },
      })
    },
    init_data_default(into_params) {
      this.edit = !!into_params.edit;
      this.repetition = !!into_params.repetition; // 是否重复购买
      this.disabled = !!into_params.disabled;
      if (this.edit || this.disabled || this.repetition) {
        if (into_params.id) {
          this.loading = true;
          this.$ajax({
            url: "/oms-api/purchase/OmsPurchaseOrderRpc/selectDetail.json",
            method: "post",
            data: { id: into_params.id },
            success: (res) => {
              if (!res.data)
                return this.$message.error(this.$t("label_data_loss"));
              this.getSourceData(res.data.customerId)
              if (res.data.purchaseFreight) this.transportationExpenses += Number(res.data.purchaseFreight)
              if (res.data.otherCost) this.transportationExpenses += Number(res.data.otherCost)
              if (this.repetition) {
                const form = {}
                strArr.forEach(key => {
                  form[key] = res.data[key] || ''
                })
                this.$refs.form.setData(form);
                this.$refs.totalForm.setData(form);
                this.rows = res.data.omsPurchaseOrderDetailList
                return
              }
              this.$nextTick(() => {
                this.$refs.form.setData(res.data);
                this.$refs.totalForm.setData(res.data);
                this.rows = res.data.omsPurchaseOrderDetailList
                this.$refs.form.clearValidate();
                this.$refs.totalForm.clearValidate();
              });

              this.dialogData.supplierName = res.data.supplierName
              this.dialogData.supplierId = res.data.supplierId

              this.option.rules.orderNo.required = !!res.data.purchaseSource
              this.fixTabLabel(res.data.code);
            },
            complete: () => {
              this.loading = false;
            },
          });
        }
      }
      this.fixTabLabel();
    },
    fixTabLabel(name) {
      if (this.repetition) {
        this.$emit("tagModifyLabel", "label_purchase_order_creation");
      } else if (this.edit) {
        this.$emit("tagModifyLabel", {
          _key: "label_name_code",
          name: this.$t("label_purchase_order_edit"),
          code: name || "",
        });
      } else if (this.disabled) {
        this.$emit("tagModifyLabel", "label_purchase_order_details");
      } else {
        this.$emit("tagModifyLabel", "label_purchase_order_creation");
      }
    },
    batchRemoval() {
      if (this.selection && this.selection.length) {
        const arr = []
        this.rows.forEach((item, i) => {
          if (this.selection.findIndex(op => op.id === item.id) !== -1) {
            arr.push(i)
          }
        })
        arr.reverse().forEach((op) => {
          this.$delete(this.rows, op)
        })
      } else {
        this.$message.error(this.$t('tip_please_select_order'))
      }
    },
    // 批量添加
    // batchAdd() {
    //   this.$refs.form.$refs.form.validateField("customerId");
    //   if(this.dialogData.customerId) {

    //   }
    // },
    // 添加
    add() {
      this.$refs.form.$refs.form.validateField("customerId");
      this.$refs.form.$refs.form.validateField("supplierId");
      if (this.dialogData.customerId&&this.dialogData.supplierId) {
        this.$refs.addSupplyRelationshipDialog.show()
      }
    },
    selectData(data,queryCriteria) {
      let key = 'id'
      if(queryCriteria==='supplier'){
        key = 'skuId'
      }
      this.$refs.addSupplyRelationshipDialog.hide()
      // 调用/oms-api/purchase/OmsPurchaseOrderRpc/selectHistoryPrice.json查询历史采购价
      if (data && data.length > 0) {

        const skuIds = []
        let newArr = []
        if (this.rows.length === 0) {
          newArr = JSON.parse(JSON.stringify(data)).map(item => {
            item.skuId = item[key]
            if (!item.purchasePrice) {
              item.purchasePrice = item.skuPrice
            }

            skuIds.push(item.skuId)
            return { ...item, skuId: item.skuId }
          })
        } else {
          data.forEach(item => {
            item.skuId = item[key]
            if (!item.purchasePrice) {
              item.purchasePrice = item.skuPrice
            }
            skuIds.push(item.skuId)
            newArr.push({ ...item, skuId: item.skuId })
            // 如果原来表格里有的商品 则不加入
            for (let index = 0; index < this.rows.length; index++) {
              const element = this.rows[index];
              if (item.skuId === element.skuId) {
                newArr.pop()
                skuIds.pop()
                break
              }
            }
          })
        }
        if (skuIds.length > 0) {
          this.rows.push(...newArr)
          this.getHistoryPrice(skuIds)
        }

      }
    },
    // 查询历史最新价格
    getHistoryPrice(skuIds) {
      this.$ajax({
        url: '/oms-api/purchase/OmsPurchaseOrderRpc/selectHistoryPrice.json',
        method: "post",
        type: "form",
        data: { skuIds },
        success: (res) => {
          if (res && res.data && res.data.rows.length > 0) {
            for (let index = 0; index < this.rows.length; index++) {
              const item = this.rows[index];
              for (let j = 0; j < res.data.rows.length; j++) {
                const item2 = res.data.rows[j];
                if (item.skuId === item2.skuId) {
                  this.$set(this.rows[index],'historyPurchasePrice',item2.skuPrice)
                }
              }
            }
            console.log('rows',this.rows)
          }

        },
      });
    },
    // type  0保存 1保存并提交审核 2保存并通过审核
    submitForm(type = 0) {
      if (this.rows.length === 0) {
        return this.$message.error(this.$t('tip_please_select_sku'))
      }
      if (this.rows.findIndex(item => !item.purchaseQty) !== -1) {
        return this.$message.error(this.$t('label_quantity_goods_no_empty'))
      }
      if (this.rows.findIndex(item => !item.purchasePrice) !== -1) {
        return this.$message.error(this.$t('label_unit_price_goods_no_empty'))
      }
      const addUrlList = [
        '/oms-api/purchase/OmsPurchaseOrderRpc/saveDraft.json',
        '/oms-api/purchase/OmsPurchaseOrderRpc/saveDraftAndSubmit.json',
        '/oms-api/purchase/OmsPurchaseOrderRpc/saveDraftAndPass.json',
      ]
      const editUrlList = [
        '/oms-api/purchase/OmsPurchaseOrderRpc/updateDraft.json',
        '/oms-api/purchase/OmsPurchaseOrderRpc/updateDraftAndSubmit.json',
        '/oms-api/purchase/OmsPurchaseOrderRpc/updateDraftAndPass.json',
      ]
      let url = (this.edit && !this.repetition)
        ? editUrlList[type]
        : addUrlList[type];
      this.$refs["form"].validate((valid, obj) => {
        if (valid) {
          const data = {
            ...this.$refs.form.getFormData(),
            ...this.$refs.totalForm.getFormData(),
            omsPurchaseOrderDetailList: this.rows,
            skuCategoryCount: this.rows.length,
            skuTotalAmount: this.skuTotalAmount,
            skuCount: this.totalNum,
            totalAmount: this.totalAmount,
          }
          this.$ajax({
            url,
            method: "post",
            type: "json",
            loading: this.$t("tip_submiting"),
            data,
            success: (res) => {
              this.$message.success(this.$t("tip_submit_success"));
              this.return_emit(null, "reload");
              this.return_page_back();
            },
          });
        } else {
          this.$message.error(this.$t("form_validate_error"));
          return false;
        }
      });
    },
  },
  destroyed() { },
};
</script>

<style lang="less" scoped>
.purchaseOrderCreationTable {
  /deep/.ex_table_auto {
    margin-bottom: 0;
  }
}

.totalCard {
  width: 100%;
  box-sizing: border-box;
  padding: 18px 10px 0 10px;
  border: 1px solid #d9dfe7;
  border-top: none;

  .el-form {
    flex: 1;
    flex-shrink: 0;
  }

  .statisticsCard {
    width: 300px;
    height: auto;
    color: #606266;

    >div {
      display: flex;
      margin-bottom: 5px;

      span {
        display: inline-block;
        width: 150px;

        &:first-child {
          text-align: right;
        }

        &:last-child {
          overflow-wrap: break-word;
        }
      }
    }
  }
}

.footerSub {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #606266;
  font-weight: 500;
  line-height: 25px;

  >div {
    display: flex;
    gap: 20px;
  }

}

.flexBox {
  display: flex;
  justify-content: center;
  align-items: center;
}

/deep/.cubs {
  color: #2ea7e0;
  cursor: pointer;
}

.label_before::before {
  content: "*";
  color: red;
}
</style>
